<template>
  <div class="login-container">
    <van-nav-bar title="登录" />
    <van-form @submit="onSubmit" :disabled="isLoading">
      <van-field
        v-model="mobile"
        required
        name="mobile"
        label="手机号"
        placeholder="手机号"
        :rules="[
          { required: true, message: '手机号不能为空' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '请输入正确的格式'
          }
        ]"
      />
      <van-field
        v-model="code"
        required
        name="code"
        label="验证码"
        placeholder="验证码"
        :rules="[
          { required: true, message: '请填写验证码' },
          { pattern: /\d{6}/, message: '请输入正确格式' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :loading="isLoading"
          :disabled="isLoading"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { userLogin } from '../../api/login'
import { saveToken } from '../../utils/token'
export default {
  data () {
    return {
      mobile: '13662613212',
      code: '246810',
      isLoading: false
    }
  },
  methods: {
    onSubmit (values) {
      this.isLoading = true
      // console.log('submit', values)
      userLogin(values)
        .then(res => {
          console.log(res)
          setTimeout(() => {
            this.isLoading = false
            this.$toast.success('登录成功')
            saveToken(res.data.data)

            // 判断是否有 redirect参数
            const redirect = this.$route.query.redirect
            if (redirect) {
              return this.$router.push({
                path: redirect
              })
            }
            // 没有 redirect

            this.$router.push({ path: '/home' })
          }, 1000)
        })
        .catch(res => {
          console.log(res)
          setTimeout(() => {
            this.isLoading = false
            this.$toast.fail('登录失败')
          }, 1000)
        })
    }
  }
}
</script>

<style lang="less">
.login-container {
  .van-nav-bar {
    background-color: #3196fa;
    .van-nav-bar__title {
      color: white;
    }
  }
}
</style>
